package com.lyh.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyh.common.annotation.DataScope;
import com.lyh.common.constant.CacheConstants;
import com.lyh.common.constant.UserConstants;
import com.lyh.common.core.domain.AjaxResult;
import com.lyh.common.core.domain.entity.SysDictData;
import com.lyh.common.core.domain.entity.SysRole;
import com.lyh.common.core.domain.entity.SysUser;
import com.lyh.common.core.domain.model.SysUserAddOrUpdateBody;
import com.lyh.common.core.domain.model.SysUserBody;
import com.lyh.common.core.redis.RedisCache;
import com.lyh.common.enums.*;
import com.lyh.common.exception.ServiceException;
import com.lyh.common.exception.user.CaptchaException;
import com.lyh.common.exception.user.CaptchaExpireException;
import com.lyh.common.utils.HttpUtils;
import com.lyh.common.utils.SecurityUtils;
import com.lyh.common.utils.StringUtils;
import com.lyh.common.utils.bean.BeanUtils;
import com.lyh.common.utils.bean.BeanValidators;
import com.lyh.system.domain.*;
import com.lyh.system.domain.req.*;
import com.lyh.system.domain.resp.AchievementsResp;
import com.lyh.system.domain.vo.AchievementsVo;
import com.lyh.system.domain.vo.InviteInfoVo;
import com.lyh.system.domain.vo.MyInviteVo;
import com.lyh.system.domain.vo.UpdateUserVo;
import com.lyh.system.mapper.*;
import com.lyh.system.service.ISysConfigService;
import com.lyh.system.service.ISysUserService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 用户 业务层处理
 *
 * @author lyh
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private OperationInfoMapper operationInfoMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private AssetMapper assetMapper;

    @Autowired
    private FaceInfoMapper faceInfoMapper;
    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;
    @Autowired
    protected RechargeRecordMapper rechargeRecordMapper;

    @Value("${aliyun.AppCode:}")
    private String applyCode;

    @Autowired
    private RedisCache redisCache;


    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> getUserList(SysUserBody user) {
        List<SysUser> userList = userMapper.getUserList(user);
        if (userList != null && userList.size() > 0) {
            List<SysDictData> memberDictData = dictDataMapper.selectDictDataByType(DictTypeEnum.member_level.getCode());
            List<SysDictData> mstoreData = dictDataMapper.selectDictDataByType(DictTypeEnum.mstore_level.getCode());
            userList.forEach(c -> {
                c.setStatusName(UserStatus.getEnum(c.getStatus()).getInfo());
                c.setTopInviteName(YesOrNoEnum.getEnum(c.getTopInviteFlag()).getInfo());
                c.setTopUserFlagName(YesOrNoEnum.getEnum(c.getTopUserFlag()).getInfo());
                //获取会员等级
                List<SysDictData> memberList = memberDictData.stream().filter(a -> a.getDictValue().equals(c.getMemberLeve())).collect(Collectors.toList());
                if (memberList != null && memberList.size() > 0) {
                    c.setMemberLeveName(memberList.get(0).getDictLabel());
                }

                List<SysDictData> mstoreList = mstoreData.stream().filter(a -> a.getDictValue().equals(c.getMstoreLeve())).collect(Collectors.toList());
                if (mstoreList != null && mstoreList.size() > 0) {
                    c.setMstoreLeveNmae(mstoreList.get(0).getDictLabel());
                }
            });
        }
        return userList;
    }

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MemberPurchaseInfoMapper memberPurchaseInfoMapper;

    @Autowired
    private UserPayRecordMapper userPayRecordMapper;
    @Autowired
    private UserCashAdvanceMapper userCashAdvanceMapper;

    @Override
    public List<SysUser> getSaleUserList(SysUserBody user) {
        List<SysUser> userList = userMapper.getYjByUserId(user);
        if (userList != null && userList.size() > 0) {
            List<SysDictData> memberDictData = dictDataMapper.selectDictDataByType(DictTypeEnum.member_level.getCode());
            List<SysDictData> mstoreData = dictDataMapper.selectDictDataByType(DictTypeEnum.mstore_level.getCode());
            userList.forEach(c -> {
                //获取会员等级
                List<SysDictData> memberList = memberDictData.stream().filter(a -> a.getDictValue().equals(c.getMemberLeve())).collect(Collectors.toList());
                if (memberList != null && memberList.size() > 0) {
                    c.setMemberLeveName(memberList.get(0).getDictLabel());
                }
                List<SysDictData> mstoreList = mstoreData.stream().filter(a -> a.getDictValue().equals(c.getMstoreLeve())).collect(Collectors.toList());
                if (mstoreList != null && mstoreList.size() > 0) {
                    c.setMstoreLeveNmae(mstoreList.get(0).getDictLabel());
                }
            });
        }
        return userList;
    }

    @Override
    public List<SysUser> getAccountList(SysUserBody user) {
        List<SysUser> userList = userMapper.getAccountUserList(user);
        if (userList != null && userList.size() > 0) {
            List<SysDictData> memberDictData = dictDataMapper.selectDictDataByType(DictTypeEnum.member_level.getCode());
            List<SysDictData> mstoreData = dictDataMapper.selectDictDataByType(DictTypeEnum.mstore_level.getCode());
            userList.forEach(c -> {
                c.setStatusName(UserStatus.getEnum(c.getStatus()).getInfo());
                c.setTopInviteName(YesOrNoEnum.getEnum(c.getTopInviteFlag()).getInfo());
                c.setTopUserFlagName(YesOrNoEnum.getEnum(c.getTopUserFlag()).getInfo());
                //获取会员等级
                List<SysDictData> memberList = memberDictData.stream().filter(a -> a.getDictValue().equals(c.getMemberLeve())).collect(Collectors.toList());
                if (memberList != null && memberList.size() > 0) {
                    c.setMemberLeveName(memberList.get(0).getDictLabel());
                }

                List<SysDictData> mstoreList = mstoreData.stream().filter(a -> a.getDictValue().equals(c.getMstoreLeve())).collect(Collectors.toList());
                if (mstoreList != null && mstoreList.size() > 0) {
                    c.setMstoreLeveNmae(mstoreList.get(0).getDictLabel());
                }
            });
        }
        return userList;
    }


    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertUser(SysUser user) {
        // 新增用户信息
        if (StringUtils.isEmpty(user.getPassword())) {
            return AjaxResult.error("密码不为空");
        }
        if (!checkUserNameUnique(user)) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        user.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int rows = userMapper.insertUser(user);
        return AjaxResult.success();
    }


    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }


    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectById(userId);

    }

    @Override
    public SysUser selectUserByTelephone(String telephone) {
        return userMapper.selectUserByTelephone(telephone);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }


    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();

        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.getIsAdmin() == 1) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
//        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
//        {
//           /* SysUser user = new SysUser();
//            user.setUserId(userId);
//            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
//            if (StringUtils.isEmpty(users))
//            {
//                throw new ServiceException("没有权限访问用户数据！");
//            }*/
//        }
    }


    @Override
    @Transactional
    public AjaxResult saveOrUpdatetUser(SysUserAddOrUpdateBody cond) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(cond, user);
        if (user.getUserId() == null) {
            if (!checkUserNameUnique(user)) {
                return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
            } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !checkPhoneUnique(user)) {
                return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
            }
            user.setCreateBy(SecurityUtils.getLoginUser().getUsername());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            insertUser(user);
        } else {
            SysUser sysUser = userMapper.selectUserById(cond.getUserId());
            sysUser.setNickName(cond.getNickName());
            sysUser.setUserName(cond.getUserName());
            sysUser.setStatus(cond.getStatus());
            sysUser.setPhonenumber(cond.getPhonenumber());
            sysUser.setUpdateTime(new Date());
            userMapper.updateUser(sysUser);
            userRoleMapper.deleteUserRoleByUserId(cond.getUserId());
            insertUserRole(sysUser);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult updatetPswUser(SysUserAddOrUpdateBody cond) {
        SysUser sysUser = userMapper.selectUserById(cond.getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(cond.getPassword()));
        sysUser.setNickName(cond.getNickName());
        sysUser.setUserName(cond.getUserName());
        sysUser.setStatus(cond.getStatus());
        sysUser.setPhonenumber(cond.getPhonenumber());
        sysUser.setUpdateTime(new Date());
        userMapper.updateUser(sysUser);
        userRoleMapper.deleteUserRoleByUserId(cond.getUserId());
        insertUserRole(sysUser);
        return AjaxResult.success();
    }

    @Override
    public int updatetPassword(SysUserPasswordReq req) {
        validateCaptcha(req.getPhonenumber(), req.getCode());

        List<SysUser> sysUsers = userMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhonenumber, req.getPhonenumber())
                .ne(SysUser::getDelFlag, 2));
        if (sysUsers == null || sysUsers.size() == 0) {
            throw new ServiceException("未找到该用户！");
        }
        SysUser sysUser = sysUsers.get(0);
        if (!sysUser.getPhonenumber().equals(req.getPhonenumber())) {
            throw new ServiceException("非原手机号！");
        }

        if (!req.getNewPassword().equals(req.getConformPassword())) {
            throw new ServiceException("前后密码不一致！");
        }
        sysUser.setPassword(SecurityUtils.encryptPassword(req.getNewPassword()));
        userMapper.updateUser(sysUser);
        return 1;
    }

    public void validateCaptcha(String telephone, String code) {

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY_PSD + telephone;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {

        Asset asset = new Asset();
        asset.setAccountBalance(new BigDecimal("0.00"));
        asset.setEquityLimit(new BigDecimal("0.0000"));
        asset.setEquityPoints(0L);
        asset.setAssetEvidenceNum(new BigDecimal("0.0000"));
        asset.setIntegral(0L);
        asset.setConsumerCouponNum(new BigDecimal("0.0000"));
        asset.setChanges(new BigDecimal("0.00"));
        int insertUser = userMapper.insert(user);
        asset.setUserId(user.getUserId());
        int insertAsset = assetMapper.insert(asset);
        return insertUser > 0 && insertAsset > 0;
    }

    @Override
    public SysUser testRegister(SysUser user) {

        Asset asset = new Asset();
        asset.setAccountBalance(new BigDecimal("0.00"));
        asset.setEquityLimit(new BigDecimal("0.0000"));
        asset.setEquityPoints(0L);
        asset.setAssetEvidenceNum(new BigDecimal("0.0000"));
        asset.setIntegral(0L);
        asset.setConsumerCouponNum(new BigDecimal("0.0000"));
        asset.setChanges(new BigDecimal("0.00"));
        int insertUser = userMapper.insert(user);
        asset.setUserId(user.getUserId());
        int insertAsset = assetMapper.insert(asset);
        return user;
    }

    /**
     * 修改保存用户信息
     *
     * @param req 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser req) {

        boolean isExistUser = false;
        Long userId = req.getUserId();
        SysUser sysUser = userMapper.selectById(userId);
        if (sysUser == null) {
            throw new ServiceException("用户不存在");
        }
        if (req.getMemberLeve() != null) {
            isExistUser = true;
            sysUser.setMemberLeve(req.getMemberLeve());
        }
        if (req.getMstoreLeve() != null) {
            isExistUser = true;
            sysUser.setMstoreLeve(req.getMstoreLeve());
            if (req.getMstoreLeve().equals("0")) {
                sysUser.setIsMstore(false);
            } else {
                sysUser.setIsMstore(true);
            }
        }
        if (StringUtils.isNotEmpty(req.getStatus())) {
            isExistUser = true;
            sysUser.setStatus(req.getStatus());
        }
        Integer topInviteFlag1 = req.getTopInviteFlag();//条件
        Integer topInviteFlag = sysUser.getTopInviteFlag();//原

        if (req.getRebatesFlag() != null) {
            isExistUser = true;
            sysUser.setRebatesFlag(req.getRebatesFlag());
        }
        if (req.getRebatesRate() != null) {
            isExistUser = true;
            sysUser.setRebatesRate(req.getRebatesRate());
        }
        //若原不是顶级,修改为顶级
        List<SysUser> users = new ArrayList<>();
        if (topInviteFlag1 != null && sysUser.getIsAdmin() == 0) {
            isExistUser = true;
            if (topInviteFlag1 == 1 && topInviteFlag == 0) {
                if (sysUser.getTopUserFlag() == 1) {
                    //如果这个人存在顶级人，则这个人不能被设置为顶级邀请人
                    throw new ServiceException("这个人存在顶级人，则这个人不能被设置为顶级邀请人!");
                }
                //添加码
                sysUser.setTopInviteFlag(topInviteFlag1);
                sysUser.setTopInviteCode(sysUser.getMemberId().toString());
                //遍历数据修改
                List<SysUser> userList = userMapper.selectList(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getStatus, 0)
                        .eq(SysUser::getIsAdmin, 0));
                //查此用户的所有下级
                loopUser(users, userList, userId);
                if (users != null && users.size() > 0) {
                    SysUser sysUser1 = new SysUser();
                    sysUser1.setTopUserId(userId);
                    sysUser1.setTopUserFlag(1);
                    userMapper.update(sysUser1, new LambdaQueryWrapper<SysUser>()
                            .in(SysUser::getUserId, users.stream()
                                    .map(SysUser::getUserId)
                                    .collect(Collectors.toList())));
                }


            } else if (topInviteFlag1 == 0 && topInviteFlag == 1) {
                //清空
                sysUser.setTopInviteFlag(topInviteFlag1);
                sysUser.setTopInviteCode("");

                List<SysUser> userList = userMapper.selectList(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getStatus, 0)
                        .eq(SysUser::getIsAdmin, 0));
                //查此用户的所有下级
                loopUserNo(users, userList, userId);
                if (users != null && users.size() > 0) {
                    SysUser sysUser1 = new SysUser();
                    sysUser1.setTopUserId(0l);
                    sysUser1.setTopUserFlag(0);
                    userMapper.update(sysUser1, new LambdaQueryWrapper<SysUser>().in(SysUser::getUserId, users.stream().map(SysUser::getUserId).collect(Collectors.toList())));

                }
            }
        }
        if (isExistUser) {
            userMapper.updateById(sysUser);
        }
        Asset asset = assetMapper.selectAssetByUserId(req.getUserId());
        boolean isExistAsset = false;
        if (req.getIntegral() != null) {

            //若前后积分不等则加记录
            if (req.getIntegral() != asset.getIntegral()) {

                OperationInfo info = new OperationInfo();
                info.setPrice(new BigDecimal(req.getIntegral()));
                info.setUserId(asset.getUserId());
                info.setOperationTime(new Date());
                info.setOrigin(OperationOriginEnum.bo_integral.name());
                info.setStatus(OperationStatusEnum.RECORD.name());
                info.setType(OperationTypeEnum.RECORD.name());
                info.setCreateBy(SecurityUtils.getUsername());
                operationInfoMapper.insert(info);
            }

            asset.setIntegral(req.getIntegral());


            isExistAsset = true;
        }
        if (req.getAssetEvidenceNum() != null) {

            //若前后积分不等则加记录
            if (req.getAssetEvidenceNum() != asset.getAssetEvidenceNum()) {

                OperationInfo info = new OperationInfo();
                info.setPrice(req.getAssetEvidenceNum());
                info.setUserId(asset.getUserId());
                info.setOperationTime(new Date());
                info.setOrigin(OperationOriginEnum.bo_assetEvidenceNum.name());
                info.setStatus(OperationStatusEnum.RECORD.name());
                info.setType(OperationTypeEnum.RECORD.name());
                info.setCreateBy(SecurityUtils.getUsername());
                operationInfoMapper.insert(info);
            }

            isExistAsset = true;
            asset.setAssetEvidenceNum(req.getAssetEvidenceNum());
        }
        if (req.getConsumerCouponNum() != null) {

            //若前后积分不等则加记录
            if (req.getConsumerCouponNum() != asset.getConsumerCouponNum()) {

                OperationInfo info = new OperationInfo();
                info.setPrice(req.getConsumerCouponNum());
                info.setUserId(asset.getUserId());
                info.setOperationTime(new Date());
                info.setOrigin(OperationOriginEnum.bo_consumerCouponNum.name());
                info.setStatus(OperationStatusEnum.RECORD.name());
                info.setType(OperationTypeEnum.RECORD.name());
                info.setCreateBy(SecurityUtils.getUsername());
                operationInfoMapper.insert(info);
            }


            isExistAsset = true;
            asset.setConsumerCouponNum(req.getConsumerCouponNum());
        }

        if (req.getEquityLimit() != null) {

            //若前后积分不等则加记录
            if (req.getEquityLimit() != asset.getEquityLimit()) {

                OperationInfo info = new OperationInfo();
                info.setPrice(req.getEquityLimit());
                info.setUserId(asset.getUserId());
                info.setOperationTime(new Date());
                info.setOrigin(OperationOriginEnum.bo_limit.name());
                info.setStatus(OperationStatusEnum.RECORD.name());
                info.setType(OperationTypeEnum.RECORD.name());
                info.setCreateBy(SecurityUtils.getUsername());
                operationInfoMapper.insert(info);
            }


            isExistAsset = true;
            asset.setEquityLimit(req.getEquityLimit());
        }

        if (req.getAccountBalance() != null) {

            //若前后积分不等则加记录
            if (req.getAccountBalance() != asset.getAccountBalance()) {

                OperationInfo info = new OperationInfo();
                info.setPrice(req.getAccountBalance());
                info.setUserId(asset.getUserId());
                info.setOperationTime(new Date());
                info.setOrigin(OperationOriginEnum.bo_accountBalance.name());
                info.setStatus(OperationStatusEnum.RECORD.name());
                info.setType(OperationTypeEnum.RECORD.name());
                info.setCreateBy(SecurityUtils.getUsername());
                operationInfoMapper.insert(info);
            }

            isExistAsset = true;
            asset.setAccountBalance(req.getAccountBalance());
        }

        if (req.getChanges() != null) {

            //若前后积分不等则加记录
            if (req.getChanges() != asset.getChanges()) {

                OperationInfo info = new OperationInfo();
                info.setPrice(req.getChanges());
                info.setUserId(asset.getUserId());
                info.setOperationTime(new Date());
                info.setOrigin(OperationOriginEnum.bo_change.name());
                info.setStatus(OperationStatusEnum.RECORD.name());
                info.setType(OperationTypeEnum.RECORD.name());
                info.setCreateBy(SecurityUtils.getUsername());
                operationInfoMapper.insert(info);
            }

            isExistAsset = true;
            asset.setChanges(req.getChanges());
        }


        if (isExistAsset) {
            assetMapper.updateById(asset);
        }

        return 1;
    }

    @Override
    public int addAccountUser(AccountAddReq req) {
        SysUser user = new SysUser();
        user.setNickName(req.getNickName());
        user.setUserName(req.getPhonenumber());
        user.setPhonenumber(req.getPhonenumber());
        //检查是否已使用
        List<SysUser> sysUsers = userMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhonenumber, req.getPhonenumber()));
        if (sysUsers != null && sysUsers.size() > 0) {
            throw new ServiceException("手机号已经被使用，请换个手机号！");
        }
        user.setPassword(SecurityUtils.encryptPassword("888888"));
        user.setStatus(UserStatus.OK.getCode());
        user.setIsAdmin(1);
        userMapper.insert(user);
        return 1;
    }

    @Override
    public int editAccountUser(AccountEditReq req) {
        SysUser sysUser = userMapper.selectById(req.getUserId());
        if (StringUtils.isNotEmpty(req.getStatus())) {
            sysUser.setStatus(req.getStatus());
        }
        //查询手机号是否已经被使用
        if (StringUtils.isNotEmpty(req.getPhonenumber())) {
            List<SysUser> sysUsers = userMapper.selectList(new LambdaQueryWrapper<SysUser>()
                    .and(w -> w.eq(SysUser::getUserName, req.getPhonenumber()).or()
                            .eq(SysUser::getPhonenumber, req.getPhonenumber()))
                    .in(SysUser::getStatus, 0, 1)
                    .ne(SysUser::getUserId, req.getUserId()));
            if (sysUsers != null && sysUsers.size() > 0) {
                throw new ServiceException("该手机号已经被使用");
            }

            sysUser.setPhonenumber(req.getPhonenumber());
            sysUser.setUserName(req.getPhonenumber());
        }
        if (StringUtils.isNotEmpty(req.getNickName())) {
            sysUser.setNickName(req.getNickName());
        }
        return userMapper.updateById(sysUser);
    }

    @Override
    public int editAccountPsdByAdmin(AccountPsdReq req) {

        Long userId = SecurityUtils.getLoginUser().getUserId();
        SysUser sysUser1 = userMapper.selectById(userId);
        Integer isAdmin = sysUser1.getIsAdmin();
        if (isAdmin != 1 && isAdmin != 9) {
            throw new ServiceException("无管理员权限！");
        }
        SysUser sysUser = userMapper.selectById(req.getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(req.getPassword()));

        return userMapper.updateById(sysUser);
    }

    private void loopUser(List<SysUser> users, List<SysUser> userList, Long userId) {

        List<SysUser> userList0 = userList.stream().filter(c -> userId.equals(c.getParentId())).collect(Collectors.toList());
        if (userList0 != null && userList0.size() > 0) {
            userList0.stream().forEach(c0 -> {
                c0.setTopUserFlag(1);
                c0.setTopUserId(userId);
                users.add(c0);
                loopUser(users, userList, c0.getUserId());
            });
        }
    }

    private void loopUserNo(List<SysUser> users, List<SysUser> userList, Long userId) {
        List<SysUser> userList0 = userList.stream().filter(c -> c.getParentId() == userId).collect(Collectors.toList());
        if (userList0 != null && userList0.size() > 0) {
            userList0.stream().forEach(c0 -> {
                c0.setTopUserFlag(0);
                c0.setTopUserId(0l);
                users.add(c0);
                loopUser(users, userList, c0.getUserId());
            });
        }
    }


    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }


    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);

        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
//        for (Long userId : userIds)
//        {
//            checkUserAllowed(new SysUser(userId));
//            checkUserDataScope(userId);
//        }
        // 删除用户与角色关联
        //       userRoleMapper.deleteUserRole(userIds);

        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void updateUserInfo(UpdateUserVo user) {
        SysUser sysUser = userMapper.selectById(user.getUserId());
        if (user.getBeforePayPassword() != null && user.getNewPayPassword() != null && !"".equals(user.getBeforePayPassword())) {
            if (SecurityUtils.matchesPassword(user.getBeforePayPassword(), sysUser.getPayPassword())) {
                sysUser.setPayPassword(SecurityUtils.encryptPassword(user.getNewPayPassword()));
            }
        }
        if (sysUser.getPayPassword() == null && user.getNewPayPassword() != null) {
            sysUser.setPayPassword(SecurityUtils.encryptPassword(user.getNewPayPassword()));
        }
        sysUser.setNickName(user.getNickName());
        sysUser.setPhonenumber(user.getPhonenumber());
        sysUser.setAvatar(user.getAvatar());
        sysUser.setSex(user.getSex());
        sysUser.setUpdateBy(user.getNickName());
        sysUser.setBirthday(user.getBirthday());
        sysUser.setRealName(user.getRealName());
        sysUser.setZfbAccount(user.getZfbAccount());
        userMapper.updateUserInfo(sysUser);
    }

    @Override
    public MyInviteVo inviteInfo(Long userId, String type) {
        MyInviteVo myInviteVo = userMapper.inviteInfo(userId);
        if (myInviteVo != null) {
            if (myInviteVo.getAllInviteNum() != null && myInviteVo.getRechargeNum() != null) {
                myInviteVo.setNoRechargeNum(myInviteVo.getAllInviteNum() - myInviteVo.getRechargeNum());
            }

            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id", userId);
            queryWrapper.eq("status", 0);
            List<SysUser> sysUsers = userMapper.selectList(queryWrapper);

            List<MemberPurchaseInfo> memberPurchaseInfoList = memberPurchaseInfoMapper.selectList(new LambdaQueryWrapper<>());
            List<Long> longList = memberPurchaseInfoList.stream().map(MemberPurchaseInfo::getUserId).collect(Collectors.toList());

            List<InviteInfoVo> infoVoList = new ArrayList<>();
            for (SysUser sysUser : sysUsers) {
                InviteInfoVo inviteInfo = new InviteInfoVo();
                inviteInfo.setInvitePersonCode(sysUser.getMemberId());
                inviteInfo.setInviteTime(sysUser.getCreateTime());
                if ("STORE".equals(type) && sysUser.getIsVip() != 1) {
                    if (sysUser.getIsVip() == 0) {
                        inviteInfo.setStatus(RechargeEnum.STORE_NO_ACTIVE.name());
                    } else if (sysUser.getIsVip() == 2 || sysUser.getIsVip() == 3) {
                        inviteInfo.setStatus(RechargeEnum.STORE_ACTIVE.name());
                    }
                    infoVoList.add(inviteInfo);
                } else if ("ONLINE".equals(type) && sysUser.getIsVip() != 2) {
                    if (longList.contains(sysUser.getUserId())) {
                        if (sysUser.getIsVip() == 0) {
                            inviteInfo.setStatus(RechargeEnum.ONLINE_NO_ACTIVE_SCHEDULED.name());
                        } else if (sysUser.getIsVip() == 1 || sysUser.getIsVip() == 3) {
                            inviteInfo.setStatus(RechargeEnum.ONLINE_ACTIVATE_SCHEDULED.name());
                        }
                    } else {
                        if (sysUser.getIsVip() == 0) {
                            inviteInfo.setStatus(RechargeEnum.ONLINE_NO_ACTIVE.name());
                        } else if (sysUser.getIsVip() == 1 || sysUser.getIsVip() == 3) {
                            inviteInfo.setStatus(RechargeEnum.ONLINE_ACTIVATE_UNSCHEDULED.name());
                        }
                    }
                    infoVoList.add(inviteInfo);
                }
            }
            myInviteVo.setInfoVoList(infoVoList);
        }
        return myInviteVo;
    }

    @Override
    public AjaxResult realFaceCert(SysFaceInFoReq req) {
        FaceInfo faceInfo;
        List<FaceInfo> faceInfos = faceInfoMapper.selectList(new LambdaQueryWrapper<FaceInfo>()
                .eq(FaceInfo::getUserId, req.getUserId()));
        SysUser sysUser = userMapper.selectById(req.getUserId());
        if (faceInfos != null && faceInfos.size() > 0) {
            faceInfo = faceInfos.get(0);
        } else {
            faceInfo = new FaceInfo();
        }
        faceInfo.setUserId(req.getUserId());
        faceInfo.setBackUrl(req.getBackUrl());
        faceInfo.setFrontUrl(req.getFrontUrl());
        faceInfo.setIdCard(req.getIdCard());
        faceInfo.setName(req.getName());

        String host = "https://dfidveri.market.alicloudapi.com";
        String path = "/verify_id_name";
        String method = "POST";
        String appcode = applyCode;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("id_number", req.getIdCard());
        bodys.put("name", req.getName());
        Integer result = 2;
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            if (response != null) {
                String s = EntityUtils.toString(response.getEntity());
                int statusCode = response.getStatusLine().getStatusCode();
                if (StringUtils.isNotEmpty(s)) {
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String status = jsonObject.getString("status");
                    if ("OK".equals(status) && statusCode == 200) {
                        String state = jsonObject.getString("state");
                        if ("1".equals(state)) {
                            //成功
                            result = 1;
                            sysUser.setFaceIdentifyFlag(true);
                            userMapper.updateById(sysUser);
                        } else if ("2".equals(state)) {
                            //二要素不一致
                            result = 2;
                            sysUser.setFaceIdentifyFlag(false);
                            userMapper.updateById(sysUser);
                        }
                    } else if ("INVALID_ARGUMENT".equals(status)) {
                        //请求参数错误
                        throw new ServiceException("请求参数错误");
                    } else if ("unauthorized / Quota Exhausted".equals(status)) {
                        //秘钥信息错误/套餐余额用完
                        throw new ServiceException("秘钥信息错误/套餐余额用完");
                    } else if ("unauthorized".equals(status)) {
                        throw new ServiceException("秘钥信息错误");
                    } else if ("Quota Exhausted".equals(status)) {
                        throw new ServiceException("套餐余额用完");
                    } else if ("INTERNAL_ERROR".equals(status)) {
                        throw new ServiceException("服务器内部错误");
                    } else {
                        faceInfo.setFaceIdentifyFlag(2);
                    }

                }

            }
            faceInfo.setFaceIdentifyFlag(result);
            if (faceInfo.getId() == null) {
                faceInfoMapper.insert(faceInfo);
            } else {
                faceInfoMapper.updateById(faceInfo);
            }
/*            {
                "request_id": "TID8bf47ab6eda64476973cc5f5b6ebf57e",/调用记录ID
                "status": "OK",
                    "state": 1,         //  返回值为 1 : 查询成功, 二要素一致。  返回值为 2 : 查询成功, 二要素不一致
            }*/

     /*       {
                "status": "INVALID_ARGUMENT",
                    "result_message": "请求参数错误",
                    "request_id": "TID8bf47ab6eda64476973cc5f5b6ebf57e"
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(faceInfo);
    }

    @Override
    public AchievementsVo getAchievements() {
        SysUser u = SecurityUtils.getLoginUser().getUser();
        SysUser user = userMapper.selectById(u.getUserId());
        List<SysUser> sysUsers = userMapper.myIndirectUser(user.getIndirectInviteCodes());
        List<SysUser> sysUserList = userMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getParentId, user.getUserId()).eq(SysUser::getStatus, 0));
        sysUsers.addAll(sysUserList);
        sysUsers.add(user);

        List<Long> userIdList = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList());
        String userIds = org.apache.commons.lang3.StringUtils.join(userIdList, ",");
        BigDecimal orderAmount = orderMapper.getAmountByUserIds(userIds);
        BigDecimal reserveAmount = memberPurchaseInfoMapper.getAmountByUserIds(userIds);

        int v1Num = 0;
        AchievementsVo achievementsVo = new AchievementsVo();
        for (SysUser sysUser : sysUsers) {
            if (sysUser.getMemberLeve() != null && sysUser.getMemberLeve() >= 1) {
                v1Num++;
            }
        }
        achievementsVo.setV1Num(v1Num);
        achievementsVo.setOrderAmount(orderAmount);
        achievementsVo.setReserveAmount(reserveAmount);
        return achievementsVo;
    }

    @Override
    public AjaxResult countAllMoney(SysUserBody user) {

        AchievementsResp resp = new AchievementsResp();

        AchievementsResp order = userMapper.getOrderCount(user);
        AchievementsResp purcahse = userMapper.getPurcahseCount(user);
        AchievementsResp recharge = userMapper.getRechargeCount(user);
        AchievementsResp cash = userMapper.getCashCount(user);

        //计算金额
        //销售入账金额
        if (order != null) {
            if (order.getOrderAmount() != null) {
                resp.setOrderAmount(order.getOrderAmount());
            }
            if (order.getOnlineNum() != null) {
                resp.setOnlineNum(order.getOnlineNum());
            }
            if (order.getStoreNum() != null) {
                resp.setStoreNum(order.getStoreNum());
            }
            if (order.getShopNum() != null) {
                resp.setShopNum(order.getShopNum());
            }
            if(order.getOnlineAmount()!=null){
                resp.setOnlineAmount(order.getOnlineAmount());
            }
            if(order.getStoreAmount()!=null){
                resp.setStoreAmount(order.getStoreAmount());
            }
        }
        if (purcahse != null) {
            if (purcahse.getPurchaseAmount() != null) {
                resp.setPurchaseAmount(purcahse.getPurchaseAmount());
            }
            if (purcahse.getPurchaseNum() != null) {
                resp.setPurchaseNum(purcahse.getPurchaseNum());

            }
        }

        if (recharge != null && recharge.getRechargeAmount() != null) {
            resp.setRechargeAmount(recharge.getRechargeAmount());
        }
        if (cash != null) {
            if (cash.getCashAmount() != null) {
                resp.setCashAmount(cash.getCashAmount());
            }
            if (cash.getCashNum() != null) {
                resp.setCashNum(cash.getCashNum());
            }
        }

        return AjaxResult.success(resp);
    }
}
